<template>
  <div class="login">
    <div class="header">
      <van-icon name="cross" @click="onCross" />
    </div>
    <div class="main">
      <h2>账号登录</h2>
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="mail"
            name="邮箱"
            label="邮箱"
            placeholder="邮箱"
            :rules="formRule.mail"
          />
          <van-field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="formRule.password"
          />
        </van-cell-group>
        <div class="btn">
          <van-button round block type="primary" native-type="submit">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
    <div class="bottom">
      <van-divider class="line" @click="onRegister">
        没有账号？去注册
      </van-divider>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useLocalStorage } from '@vueuse/core'
import { Toast } from 'vant'
import { userLogin } from '../../../service/user'
import { useUserStore } from '../../../store/user'
import { formRule } from '../../../utils/form-rule'

const mail = ref()
const password = ref()
const router = useRouter()
const userStore = useUserStore()

const onCross = () => {
  router.replace('/home')
}
const onSubmit = async () => {
  const res = await userLogin({
    mail: mail.value,
    password: password.value
  })
  useLocalStorage('token', res.data.token)
  userStore.user = res.data.user
  Toast({
    message: '登录成功',
    type: 'success'
  })
  router.replace('/')
}
const onRegister = () => {
  router.push('/register')
}
</script>

<style lang="scss" scoped>
.login {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .header {
    display: flex;
    font-size: 22px;
    margin: 20px;
  }
  .main {
    display: flex;
    flex-direction: column;
    align-items: center;
    .btn {
      margin: 20px;
    }
  }
  .bottom {
    .line {
      color: #1989fa;
      border-color: #1989fa;
      padding: 20px;
    }
  }
}
</style>
